/**
 *
 */
package urban;

import java.util.ArrayList;

import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

/**
 * @author emily
 * 
 */
public class Word extends StringObject {

	String word;
	ArrayList<Sentence> sentences = new ArrayList<Sentence>();

	public Word(String word) throws XMLStreamException {
		this.word = word;
//		System.out.println(word);
		this.pop();
//		try {
//			Thread.sleep(70);
//		} catch (InterruptedException e) {
//			System.err.println("Could not sleep 5 milliseconds for: " + word);
//		}
//		new Thread(this).start();
	}

	@SuppressWarnings("static-access")
	@Override
	void fillEventInfo(XMLStreamReader reader) throws XMLStreamException {
		int eventCode = reader.next();
		if (eventCode == 1 && reader.getLocalName().equals("div")
				&& reader.getAttributeValue(0) != null
				&& reader.getAttributeValue(0).equals("example")) {
			while (true) {
				eventCode = reader.next();
				if (eventCode == reader.CHARACTERS) {
					String t = reader.getText();
					t = t.trim();
					if (!t.equalsIgnoreCase(this.word)) {
						Sentence s = new Sentence(this.word, t);
						sentences.add(s);
					}
					break;
				}
			}
		}
		reader.close();

	}

	public ArrayList<Sentence> getArrayList() {
		return this.sentences;
	}

	public String getWord() {
		return this.word;
	}

	public String toString() {
		return this.word;
	}

	public void pop() {

		int i = 1;
		boolean flag = true;
		while (flag) {
			String w = word;
			if (word.contains("#"))
				w = w.replace("#", "%23");
			if (word.contains(" "))
				w = w.replace(" ", "%20");
			if (word.contains("'"))
				w = w.replace("'", "%27");
			String link = "http://www.urbandictionary.com/define.php?term=" + w
					+ "&page=" + i;
			try {
				flag = populate(link);
			} catch (XMLStreamException e) {
				System.err
						.println("There was an XMLStreamException in Word for "
								+ w + " on page " + i);
				flag = false;
			}
			i++;
		}
	}

	@Override
	public void run() {
		// System.out.println("Word thread starting.");
//		int i = 1;
//		boolean flag = true;
//		while (flag) {
//			String w = word;
//			if (word.contains("#"))
//				w = w.replace("#", "%23");
//			if (word.contains(" "))
//				w = w.replace(" ", "%20");
//			if (word.contains("'"))
//				w = w.replace("'", "%27");
//			String link = "http://www.urbandictionary.com/define.php?term=" + w
//					+ "&page=" + i;
//			try {
//				flag = populate(link);
//			} catch (XMLStreamException e) {
//				System.err
//						.println("There was an XMLStreamException in Word for "
//								+ w + " on page " + i);
//			}
//			i++;
//		}
	}

}
